<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <!-- 登录的表单 -->
        <el-form class="login_form" :model="loginForm" :rules="roles" ref="loginForms">
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" :prefix-icon="Lock" v-model="loginForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading" class="login_btn" type="primary" size="default" @click="login">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref, onMounted } from 'vue'
import useUserStore from '@/store/modules/user'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { timeStatus } from '@/utils/time'

// store
const userStore = useUserStore()
// router
const router = useRouter()
// route
const route = useRoute()

//收集账号与密码的数据
let loginForm = reactive({ username: 'admin', password: 'atguigu123' })

// 按钮loading
let loading = ref(false)

// from表单
const loginForms = ref()
// 登录回调
const login = async () => {
  // 如果校验失败则，停止后面的代码
  loginForms.value.validate((v: boolean) => {
    if (!v) return
  })

  try {
    loading.value = true
    // 保证登录成功
    await userStore.userLogin(loginForm)

    // 发请求，拿用户信息数据
    await userStore.userInfo()

    // 当前用户是否是退出登录的
    const redirect: any = route.query.redirect // 退出来时的路由路径
    if (redirect) {
      router.push(redirect)
    } else {
      router.push('/')
    }

    ElNotification({
      type: 'success',
      title: `Hi, ${timeStatus()}！`,
      message: '欢迎回来！',
      duration: 2000,
    })
    loading.value = false
  } catch (error) {
    ElNotification({
      type: 'error',
      title: (error as Error).message,
      duration: 2000,
    })
  } finally {
    loading.value = false
  }
}

// 自定义校验规则函数
// 用户名校验规则
// @ts-ignore
const validatorUserName = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('账号不能为空'))
    // } else if (!(/^1[3|4|5|6|7|8|9]\w{9}$/.test(value))) {  // 当也许需要判断手机号时
    // callback(new Error('手机号格式不正确'))
  } else if (value.length <= 5) {
    callback(new Error('账号长度至少六位'))
  } else {
    callback()
  }
}
// 密码校验规则
// @ts-ignore
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('密码不能为空'))
    // } else if (!(/^1[3|4|5|6|7|8|9]\w{9}$/.test(value))) {  // 当也许需要判断手机号时
    // callback(new Error('手机号格式不正确'))
  } else if (value.length <= 5) {
    callback(new Error('密码长度至少六位'))
  } else {
    callback()
  }
}
// 定义表单校验需要配置对象
const roles = {
  // 规则对象属性：
  // required: 代表这个字段务必要校验的
  // min: 文本长度至少多少位
  // max: 文本长度最多多少位
  // message: 错误的提示信息
  // trigger: 触发校验表单的时机 change->文本发生变化触发校验，blur->失去焦点的时候触发校验规则

  // 用户名
  username: [
    // { required: true, min: 6, max: 10, message: '账号长度至少六位', trigger: 'change' },
    { trigger: 'change', validator: validatorUserName },
  ],
  // 密码
  password: [
    // { required: true, min: 6, max: 15, message: '密码长度至少6位', rigger: 'change' },
    { trigger: 'change', validator: validatorPassword },
  ],
}
</script>
<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login_form {
    position: relative;
    width: 80%;
    top: 30vh;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    padding: 40px;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      font-size: 20px;
      color: white;
      margin: 20px 0px;
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>
